<template>
  <div class="changepassword">
    <Form
      ref="form"
      :label-width="150"
      :rules="rules"
      labelPosition="left"
      :model="form"
    >
      <FormItem label="旧密码" prop="oldpassword">
        <input type="text" v-width="400" v-model="form.oldpassword" />
      </FormItem>
      <FormItem label="新密码" prop="newpassword1">
        <input type="password" v-width="400" v-model="form.newpassword1" />
      </FormItem>
      <FormItem label="确认新密码" prop="newpassword2">
        <input type="password" v-width="400" v-model="form.newpassword2" />
      </FormItem>
      <FormItem>
        <Button color="primary" @click="submit">提交</Button>
      </FormItem>
    </Form>
  </div>
</template>
<script>
import md5 from "md5";
export default {
  data() {
    return {
      form: {
        oldpassword: "",
        newpassword1: "",
        newpassword2: ""
      },
      rules: {
        required: ["oldpassword", "newpassword1", "newpassword2"],
        combineRules: [
          {
            refs: ["newpassword1", "newpassword2"],
            valid: {
              valid: "equal",
              message: "两次输入的密码不一致"
            }
          }
        ]
      }
    };
  },
  methods: {
    async submit() {
      let validResult = this.$refs.form.valid();
      if (validResult.result) {
        let res = await this.$post("/api/admin/changepassword", {
          oldPassWord: md5(this.form.oldpassword),
          newPassWord: md5(this.form.newpassword1)
        });
        if (res && res.code === 200) {
          this.$Message.success("修改成功，请重新登录");
          this.$router.push("/login");
          window.localStorage.token = "";
        } else {
          this.$Message.error(res.message);
        }
      } else {
        this.$Message.error(
          `还有${validResult.messages.length}个错误未通过验证。`
        );
      }
    }
  }
};
</script>
<style lang="less" scoped>
.changepassword {
  padding: 22px;
  display: flex;
  justify-content: center;
  position: relative;
  top: 50%; /*偏移*/
  transform: translateY(-50%);
}
</style>